// pages/create-vote/create-vote.ts
import { STORAGE_KEY } from "../../../api/config";

import {save,Vote,VoteOption} from "../../../api/votes"

Page({
  data: {
    voteTitle: '',
    voteDesc:'',
    options: [{ value: '' }, { value: '' }] as OptionItem[],
    isMultiSelect: false,
    maxSelect: 1,
    date: '',
    time: '23:00',
    deadlineDate: '选择日期',
    deadlineTime: '23:00:00',
    currentDate: getCurrentDate(),
    maxDate: '2099-12-31'
  },

  onTitleChange(e:any) {
    this.setData({ voteTitle: e.detail.value })
  },
  onDescripChange(e:any){
    this.setData({ voteDesc: e.detail.value })
  },

  onOptionChange(e:any) {
    const index = e.currentTarget.dataset.index
    const value = e.detail.value
    this.setData({
      [`options[${index}].value`]: value
    })
  },

  addOption() {
    if (this.data.options.length < 10) {
      this.setData({
        options: [...this.data.options, { value: '' }]
      })
    }
  },

  removeOption(e: WechatMiniprogram.TouchEvent) {
    const index = e.currentTarget.dataset.index
    if (this.data.options.length > 2) {
      this.data.options.splice(index, 1)
      this.setData({ options: this.data.options })
    }
  },

  bindDateChange(e: WechatMiniprogram.PickerChange) {
    this.setData({
      date: e.detail.value,
      deadlineDate: formatDate(e.detail.value)
    })
  },

  bindTimeChange(e: WechatMiniprogram.PickerChange) {
    this.setData({
      time: e.detail.value,
      deadlineTime: e.detail.value + ':00'
    })
  },

  toggleMultiSelect(e: WechatMiniprogram.SwitchChange) {
    this.setData({ 
      isMultiSelect: e.detail.value,
      maxSelect: e.detail.value ? 2 : 1
    })
  },

  onMaxSelectChange(e:any) {
    this.setData({ maxSelect: Number(e.detail.value) })
  },

  validateForm() {
    const { voteTitle, options, date, time } = this.data
    if (!this.validateRequired(voteTitle, '投票主题')) return
    if (options.some(opt => !opt.value.trim())) {
      wx.showToast({ title: '请填写所有选项', icon: 'none' })
      return
    }
    if (!date || !time) {
      wx.showToast({ title: '请选择截止时间', icon: 'none' })
      return
    }
    this.submitVote()
  },

  validateRequired(value: string, field: string): boolean {
    if (!value.trim()) {
      wx.showToast({ title: `请填写${field}`, icon: 'none' })
      return false
    }
    return true
  },

  async submitVote() {
    wx.showLoading({ title: '创建中...' })
    let vote:Vote = {
      title:this.data.voteTitle,
      description:this.data.voteDesc,
      endTime:dateFormat(new Date(new Date(this.data.deadlineDate+" "+this.data.deadlineTime).getTime())),
      maxChoices:this.data.maxSelect
    }
    let options:VoteOption[] = []
    this.data.options.forEach((item)=>{
      let option:VoteOption={
        content:item.value,
        voteCount:0
      }
      options.push(option)
    })
    vote.optionsList=options
    let result = await save(vote)
    if(result && result.code && result.code==20000){
      wx.showToast({ title: '创建成功！' })
      // wx.navigateBack()
      wx.redirectTo({
        url: `/pages/vote/index/index?id=${result.data}`,
        success: () => {
          // wx.vibrateShort()
        }
      })
    }
    else{
      wx.showToast({ title: '创建失败！请稍后再试' })
    }
   
  }
})

interface OptionItem {
  value: string
}

function getCurrentDate(): string {
  const date = new Date()
  return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`
}

function formatDate(dateStr: string): string {
  const [year, month, day] = dateStr.split('-')
  return `${year}-${month}-${day}`
}

/**
 * 格式化日期时间字符串
 *
 * @param value 待格式化的日期时间值，支持数字、字符串和 Date 类型，默认为当前时间戳
 * @param format 格式化字符串，默认为'YYYY-MM-DD HH:mm:ss'，支持格式化参数：YY：年，M：月，D：日，H：时，m：分钟，s：秒，SSS：毫秒
 * @returns 返回格式化后的日期时间字符串
 */
export function dateFormat(value: number | string | Date = Date.now(), format: string = 'YYYY-MM-DD HH:mm:ss'): string {
  try {
    let date: Date
    if (typeof value === 'number' || typeof value === 'string') {
      date = new Date(value)
      if (isNaN(date.getTime())) {
        throw new Error('Invalid date')
      }
    } else {
      date = value
    }
    const padZero = (value: number, len: number = 2): string => {
      // 左侧补零函数
      return String(value).padStart(len, '0')
    }
    const replacement = (match: string) => {
      switch (match) {
        case 'YYYY':
          return padZero(date.getFullYear())
        case 'YY':
          return padZero(date.getFullYear()).slice(2, 4)
        case 'MM':
          return padZero(date.getMonth() + 1)
        case 'M':
          return String(date.getMonth() + 1)
        case 'DD':
          return padZero(date.getDate())
        case 'D':
          return String(date.getDate())
        case 'HH':
          return padZero(date.getHours())
        case 'H':
          return String(date.getHours())
        case 'mm':
          return padZero(date.getMinutes())
        case 'm':
          return String(date.getMinutes())
        case 'ss':
          return padZero(date.getSeconds())
        case 's':
          return String(date.getSeconds())
        case 'SSS':
          return padZero(date.getMilliseconds(), 3)
        default:
          return match
      }
    }
    return format.replace(/(YYYY|YY|M{1,2}|D{1,2}|H{1,2}|m{1,2}|s{1,2}|SSS)/g, replacement)
  } catch (error) {
    console.error('Error formatting date:', error)
    return ''
  }
}
